$(function() {

    var adModel = Backbone.Model.extend({
        url : function() {
            var appId = getUrlParam("appid");
            var adId = getUrlParam("adid");
            if(debug) {
                return "ad.json";
            } else {
                return interfaceRoot + "/api/apps/" + appId + "/ads/" + adId;
            }
        },
        defaults : function() {
            return {
                appId : "",
                order : "",
                name : "",
                form : "",
                type : "",
                origin : "",
                startTime : "",
                endTime : "",
                displayType : "",
                text : "",
                imgUrl : "",
                clickType : "",
                adUrl : "",
                remark : "",
                status : ""
            };
        },
        initialize : function() {
            for(var key in this.defaults()) {
                if(key == "order")
                    continue;
                if(!this.get(key)) {
                    this.set({
                        key : this.defaults().key
                    });
                }
            }
        },
        parse : function(data) {//fetch,save 触发
            if(data.startTime) {//转换时间格式
                var startTime = new Date(data.startTime);
                var endTime = new Date(data.endTime);
                data.startTime = startTime.Format("yyyy-MM-dd hh:mm");
                data.endTime = endTime.Format("yyyy-MM-dd hh:mm");
            }
            console.log(data);
            return data;
        },
        validate : function(attrs, options) {
            if(!(attrs.appId && attrs.order)) {
                return "验证失败";
            }

            if(!attrs.name) {
                return "项目名验证失败";
            }

            if(!attrs.type) {
                return "广告类型证失败";
            }

            if(!attrs.origin) {
                return "广告来源证失败";
            }

            if(!attrs.startTime) {
                return "开始时间验证失败";
            }
            if(!attrs.endTime) {
                return "结束时间验证失败";
            }

            if(!attrs.adUrl) {
                return "链接地址验证失败";
            }

            if(!attrs.clickType) {
                return "点击目标类型验证失败";
            }

            if(attrs.displayType == "文字") {
                if(!attrs.text) {
                    return "广告文字内容验证失败"
                }
            }

            if(attrs.displayType == "图片") {
                if(!attrs.imgUrl) {
                    return "广告图片验证失败"
                }
            }

            if(attrs.displayType == "文字+图片") {
                if(!attrs.imgUrl) {
                    return "广告图片验证失败"
                }
                if(!attrs.text) {
                    return "广告文字内容验证失败"
                }
            }

        }
    });

    var appView = Backbone.View.extend({
        el : $("#container"),

        template : _.template($('#form-template').html()),

        events : {
            "change #displayType" : "changeDisplay",
            "click #addAdSaveButton" : "confirm",
            "click #addAdAbortButton" : "jumpToManager"
        },

        initialize : function() {//在这里初始化整个应用
            var handel = this;

            myAd.fetch({
                success : function() {
                    handel.render();
                    //改变导航栏名称
                    var appId = getUrlParam("appid");
                    var appName = getUrlParam("name");
                    var appPlatform = getUrlParam("platform");

                    $("#container .span9 .breadcrumb li:eq(1) a").text(appName + "  " + appPlatform);
                    $("#container .span9 .breadcrumb li:eq(1) a").attr("href", "manageAds.html?id=" + appId + "&name=" + appName + "&platform=" + appPlatform);
                    $("#container .span9 .breadcrumb li:eq(2)").text(myAd.get("form"));

                    //
                    var url;
                    if(debug) {
                        url = "interface.json"
                    } else {
                        url = interfaceRoot + "/api/upload/img";
                    }
                    $('#uploadImg input').fileupload({
                        url : url,
                        type : "POST",
                        dataType : 'json',
                        maxFileSize : 1024 * 10, //10kb
                        acceptFileTypes : /(\.|\/)(gif|jpe?g|png)$/i,
                        done : function(e, data) {
                            var code = data.result.code;
                            var url = data.result.imgUrl;

                            if(code == "success") {
                                handel.$("#preview img").attr("src", url);
                                myAd.set("imgUrl", url);
                            } else {
                                alert("图片上传失败，请检查文件类型与大小")
                            }
                        }
                    });
                }
            });

        },

        render : function() {

            this.$("#addAdForm").html(this.template(myAd.toJSON()));

            $(".J-datetime").datetimepicker({
                format : "yyyy-MM-dd hh:mm",
                language : "zh-CN"
            });

            //改变单选框
            this.$("select[name=type]").val(myAd.get("type"));
            this.$("select[name=origin]").val(myAd.get("origin"));
            this.$("select[name=displayType]").val(myAd.get("displayType"));
            this.$("select[name=clickType]").val(myAd.get("clickType"));

            this.changeDisplay();
        },

        changeDisplay : function() {//显示类型改变的时候
            var displayType = this.$("#displayType").val();

            switch(displayType) {
                case "文字":
                    this.$("#uploadImg").hide();
                    this.$("#adText").show();
                    this.$("#adRemark").hide();

                    break;
                case "图片":
                    this.$("#uploadImg").show();
                    this.$("#adText").hide();
                    this.$("#adRemark").show();

                    break;
                case "文字+图片":
                    this.$("#uploadImg").show();
                    this.$("#adText").show();
                    this.$("#adRemark").show();
                    break;
                default:
                    this.$("#uploadImg").hide();
                    this.$("#adText").show();
                    this.$("#adRemark").hide();
            }

        },

        confirm : function() {
            var handle = this;
            $("#confirmModal").modal();
            $("#confirmModal .btn-primary").unbind();
            $("#confirmModal .btn-primary").click(function() {

                $("#confirmModal").modal("hide");
                handle.saveAd();
            })
        },

        saveAd : function() {
            var handle = this;

            var name = this.$("input[name=name]").val();
            var type = this.$("select[name=type]").val();
            var origin = this.$("select[name=origin]").val();
            var startTime = this.$("input[name=startTime]").val();
            var endTime = this.$("input[name=endTime]").val();
            var displayType = this.$("select[name=displayType]").val();
            var text = this.$("input[name=text]").val();
            var remark = this.$("input[name=remark]").val();
            var adUrl = this.$("textarea[name=adUrl]").val();
            var clickType = this.$("select[name=clickType]").val();
            myAd.set({
                name : name,
                type : type,
                origin : origin,
                startTime : startTime,
                endTime : endTime,
                displayType : displayType,
                text : text,
                adUrl : adUrl,
                clickType : clickType,
                remark : remark
            })

            if(!myAd.isValid()) {// 验证失败
                alert(myAd.validationError);
            } else {
                myAd.save({
                    name : name,
                    type : type,
                    origin : origin,
                    startTime : startTime,
                    endTime : endTime,
                    displayType : displayType,
                    text : text,
                    adUrl : adUrl,
                    clickType : clickType,
                    remark : remark
                }, {
                    success : function(model, response) {
                        if(response["code"] == "success") {
                            alert(response["message"])
                            handle.jumpToManager();
                        } else {
                            alert(response["message"])
                        }
                    },
                    error : function(model, response) {
                        alert("添加失败")
                    }
                });

            }

            //console.log(JSON.stringify(myAd.toJSON()))

            return false;
        },

        jumpToManager : function() {
            var appName = getUrlParam("name");
            var appPlatform = getUrlParam("platform");
            var appId = getUrlParam("appid");

            var url = "manageAds.html?id=" + appId + "&name=" + appName + "&platform=" + appPlatform;
            window.location = window.encodeURI(url);
        }
    });

    var myAd = new adModel;
    var myAppView = new appView;

})
